package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 何惠民
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    //extends >>> 扩展


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        log.debug("Spring Security框架调用UserDetailsServiceImpl中的UsernameNotFoundException");

        AdminLoginInfoVO admin = adminMapper.getLoginInfoByUsername(s);
        log.debug("从数据库中根据用户名{}查询到{}",s,admin);
        if (admin == null){
            log.debug("从数据库中根据用户名{}查询到null,即将抛出异常");
            String message = "登录失败,用户名不存在";
            throw new BadCredentialsException(message);
        }

        //处理权限信息
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : admin.getPermissions()) {
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        AdminDetails adminDetails = new AdminDetails(
                admin.getId(),
                admin.getUsername(),
                admin.getPassword(),
                admin.getEnable() == 1,
                authorities
        );
//        UserDetails userDetails = User.builder()
//                .username(admin.getUsername())
//                .password(admin.getPassword())
//                .disabled(admin.getEnable() == 0)   //账号是否禁用
//                .accountLocked(false)  //账号是否锁定
//                .accountExpired(false) //账号是否过期
//                .credentialsExpired(false) //登录凭证是否过期
//                .authorities("暂时给定出的假的权限标识")  //权限
//                .build();
        log.debug("已经准备好,即将向spring security框架返回adminDetails对象");

        return adminDetails;
    }
}
